package signal

import (
	"io"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	"xp/lib/finalize"
	"xp/lib/md"
)

func ListenAndServe(closers ...io.Closer) {
	md.Get().Print()

	ch := make(chan os.Signal, 1)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
	<-ch

	// closers一般传入service或db
	// closers的优先级比较高，在这里首先关闭
	for _, close := range closers {
		if err := close.Close(); err != nil {
			log.Println(err)
		}
	}
	d := make(chan struct{}, 1)
	go func() {
		finalize.Exit()
		d <- struct{}{}
	}()
	// 等待5s，尝试清理
	// 防止死锁，无法关闭
	select {
	case <-d:
	case <-time.After(time.Second * 5):
		log.Println("clean up timeout.")
	}
	os.Exit(0)
}
